package com.hzw.saas.web.app.user.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.hzw.saas.common.config.util.AssertUtil;
import com.hzw.saas.common.util.Json;
import com.hzw.saas.web.app.user.controller.dto.SaasTokenDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author sonam
 * @sine 2021/11/19 4:35 下午
 */
@Slf4j
@RestController
@Api(tags = "用户中心/鸿之微登录")
public class UserCodeController {

    @Value("${SSO.getTokenApi:''}")
    private String getTokenApi;
    @Value("${SSO.clientId:''}")
    private String clientId;
    @Value("${SSO.secret:''}")
    private String secret;

    @ApiOperation(value = "授权码登录")
    @GetMapping("/saas/oauth2/code/login")
    public ResponseEntity<SaasTokenDto> codeLogin(@RequestParam String code) {
        AssertUtil.assertThrow("参数错误", StrUtil.isBlank(code));
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("client_id", clientId);
        map.put("client_secret", secret);
        try {
            log.debug("request: {}, params: {}", getTokenApi, map);
            String resp = HttpUtil.post(getTokenApi, map);
            SaasTokenDto saasTokenDto = Json.parseObject(resp, SaasTokenDto.class);
            AssertUtil.assertThrow("授权码无效", Objects.isNull(saasTokenDto));
            return ResponseEntity.ok(saasTokenDto);
        } catch (Exception e) {
            log.error("授权码无效", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

}
